package com.tfswx.jcyw.sqlmodel.api.bean.table;

import com.tfswx.jcyw.sqlmodel.api.bean.table.expression.WhereItem;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 张述江
 * @date 2023/9/15
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class PlainSelect extends Select {
    private List<SelectItem> selectItems = new ArrayList<>();
    private FromItem fromItem;
    private List<Join> joins;
    private WhereItem where;
    private ExpressionList groupBy;

    public PlainSelect(FromItem fromItem) {
        this.fromItem = fromItem;
    }

    public PlainSelect() {
        this(null);
    }

    public void addSelectItem(SelectItem... selectItems) {
        this.selectItems.addAll(Arrays.asList(selectItems));
    }

    public void addSelectItem(List<SelectItem> selectItems) {
        this.selectItems.addAll(selectItems);
    }

    @Override
    public StringBuilder appendSelectBodyTo(StringBuilder builder) {
        builder.append("SELECT ");

        if (selectItems.isEmpty()) {
            builder.append("*");
        } else {
            builder.append(getStringList(selectItems));
        }
        if (fromItem != null) {
            builder.append(" FROM ").append(fromItem);
        }
        if (joins != null) {
            for (Join join : joins) {
                builder.append(join);
            }
        }
        if (where != null && StringUtils.isNotBlank(where.toString())) {
            builder.append(" WHERE ").append(where);
        }
        if (groupBy != null) {
            builder.append(" ").append(groupBy);
        }

        return builder;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}
